
const Router = require('koa-router')
const router = new Router()
const dbHandle = require('../dbhandel')
const fs = require('fs')
router.prefix('/configPars')

router.get('/expressUnitPrice', async (ctx, next) => {
    await dbHandle.handelQuery('expressUnitPrice').then(function (data) {
        let res = {
            'code': data
        };
        ctx.body = data;
    }).catch(function (err) {
        if (err) { throw err };
    });
})

router.get('/del', async (ctx, next) => {
    await dbHandle.handleDelDocument({ '_id': "5de71d8864875625e266bd51" }).then(function (data) {
        let res = {
            'code': data
        };
        ctx.body = data;
    }).catch(function (err) {
        if (err) { throw err };
    });
})

// router.get('/provinces', async (ctx, next) => {
//     await dbHandle.handleQueryDistinctDocument("provinceAdcode,provinceName").then(function (data) {
//         let res = {
//             'code': data
//         };
//         ctx.body = data;
//     }).catch(function (err) {
//         if (err) { throw err };
//     });
// })

async function getData() {
    return new Promise((resolve) => {
        fs.readFile('data/priceParList.json', function (err, data) {
            if (err) throw err;
            if (data) {
                var confirgureData = data.toString();
                console.log('1 confirgureData = ' + confirgureData);
                resolve(confirgureData);
            }
        })
    });
}


router.post('/getRuleResult', async (ctx, next) => {
// router.get('/getRuleResult', async (ctx, next) => {
    // var data,req = ctx.request.body;
    var data, req = ctx.request.body;
    console.log("-- "+JSON.stringify(req));
    await getData().then(function (res) {
        console.log("2 - " + res);
        data = JSON.parse(res);
    });
    console.log("3 - " + data);
    console.log("\n4 - " + data.data);
    var parsList = data.data.parsList;
    var dataRules = data.data.value, execStr = `${dataRules}`;
    console.log('dataRules ' + dataRules);
    parsList.map(function (item) {
        execStr = execStr.replace(`{${item.parName}}`, 1);
    });
    var execStrs = `return (${execStr})`;
    // var execStrs  = `(${execStr})`;
    console.log(`\nexecStrs ${execStrs}\n`);
    var dataRS = Function(execStrs)();
    // var dataRS = execStr;
    console.log("\n" + dataRS);
    ctx.body = dataRS;

})




module.exports = router